<template>
  <v-text-field
    density="compact"
    placeholder="请输入验证码"
    prepend-inner-icon="mdi-code-tags"
    variant="outlined"
    label="验证码"
    v-model:model-value="code"
    :rules="[v => !!v || '验证码不能为空']"
    @blur="$emit('change', code)"
  >
    <template #append>
      <v-img
        class="w-32"
        gradient="to top right, rgba(100,115,201,.33), rgba(25,32,72,.3)"
        :src="captcha"
        @click="fetchCaptcha"
        lazy
      ></v-img>
    </template>
  </v-text-field>
</template>

<script setup lang="ts">
import { getCaptcha } from '@/api';
import { toast } from '@/utils';
import { ref } from 'vue';
const captcha = ref('');
const code = ref('');
const canClick = ref(true);

function fetchCaptcha() {
  if (canClick.value) {
    getCaptcha().then((res: any) => {
      const url = URL.createObjectURL(res);
      captcha.value = url;
      canClick.value = false;
      setTimeout(() => {
        canClick.value = true;
      }, 3000); // 3秒后重置canClick
    });
  } else toast('点击太快了，3秒后再点击哦', 'error');
}
fetchCaptcha();
</script>

<style scoped></style>
